//function to import javascript class
function debug(obj){
	alert("debug:"+obj);
}
var basePath="js/";
var API_PROVINCE="Hub/Province";
var API_CITY="Hub/City";
var API_RUE="Hub/Rue";
var API_REGION="Hub/Region";


var fieldName=[["csqu1","阴性(NILM)",0],
				['csqu2','非典型鳞状细胞',0],
				['cepi1','非典型腺细胞',0],
				['cepi2','非典型腺细胞(倾向瘤变)',0],
				['cepi3','宫颈管原位腺癌',0],
				['csqu3','低级别鳞状上皮内病变（LSIL）',0],
				['csqu4','高级别鳞状上皮内病变（HSIL）',0],
				['csqu5','鳞状细胞癌',0],
				['cepi4','腺癌',0],
				['cmic6','提示HPV感染',0],
				['cin_state_2','中量炎症细胞',0],
				['cin_state_3','大量炎症细胞',0],
				['cmic2','菌群异常性阴道病',0],
				['cmic3','滴虫感染',0],
				['cmic4','霉菌感染',0]
				
	];
	
function importJ(fpath){ 
   //fpath = fpath.replace(/\./g,'\/'); 
   //debug('<script src="'+ basePath + fpath + '.js" type="text\/javascript"></script>');
   document.write('<script src="'+ basePath + fpath + '.js" type="text\/javascript"></script>'); 
}

importJ('jquery-ui-1.8.6.custom.min');
importJ('jquery.form');
importJ('flexigrid');
importJ('highcharts');
function getPercent(num,total){
	num = parseFloat(num);
	total = parseFloat(total);
	if (isNaN(num) || isNaN(total)) {
		return "0%";
	}
	return total<=0?"0%":(Math.round(num / total * 10000)/100.00 + "%");
}



$(document).ready(function() {
	$("#set_query_form").ajaxForm({
			dataType:'json',
			success:processJson
	});
});
//--- global
var chart_data={};
var chart_name_data={};
chart_name_data['shandong']="山东项目统计图表";
chart_name_data['jinan']="济南项目统计图表";
chart_name_data['overall']="地区统计结果";



var chart_type="column";//column,pie
//--global

function setChart(selector){
	chart_type=selector.value;
	repaintChart();
}


function processJson(data){
	
	resetTable();
	
	var mydata=data.items;//this has been changed to use the list<itemAnalyze>
	if(mydata.length<0)
		return;
	appendTable(mydata);
	//enableChartOptions();
	//loadChart(chart_data["overall"],chart_name_data["overall"]);
	$("#analyzerBtn").css("display","block");
	$("#analyzerMsg").css("display","none");
}
function disableBtn(){
	$("#analyzerBtn").css("display","none");
	$("#analyzerMsg").css("display","block");
}
function resetTable()
{
	$("#analyzeTable").html(
			"<tbody>"+
			"<tr>"+
			//"<th>&nbsp;</th>"+
			"<th>项目类别</th>"+
			"<th>标本总量</th>"+
			"<th>阴性标本例数</th>"+
			"<th>阴性占比</th>"+
			"<th>阳性标本数量</th>"+
			"<th>阳性占比</th>"+
			"<th>细胞学阳性例数</th>"+
			"<th>阳性占比</th>"+
			"<th>详细统计信息（例数）</th>"+
			"</tr>"+
			"</tbody>"
	);
}
function enableChartOptions(){
	$("#selectChart").attr("disabled","");
	$("#setChart").attr("disabled","");
}

function appendTable(data){
	var tableLength=9;

	
	var resultItems=data;
	var className='odd';
	var toalNumberSum=0;
	var positiveNumberSum=0;
	var negativeNumberSum=0;
	var negativeNumberOfCellSum=0;

	
	var chart_cat=new Array();
	var chart_value_yinxing=new Array();
	var chart_value_yangxing=new Array();
	var chart_value_xinbaoYangxing=new Array();
	
	for(var i=0;i<resultItems.length;i++){
		var row=$("<tr/>").attr("class",className);
		//$("<td/>").html("<input type='checkbox'/>").appendTo(row);
		$("<td/>").text(resultItems[i]['name']).appendTo(row);
		$("<td/>").text(resultItems[i]['totalNumber']).appendTo(row);
		$("<td/>").text(resultItems[i]['yinXing']).appendTo(row);
		$("<td/>").text(getPercent(resultItems[i]['yinXing'],resultItems[i]['totalNumber'])).appendTo(row);
		
		var yangxing=resultItems[i]['totalNumber']-resultItems[i]['yinXing'];
		
		$("<td/>").text(yangxing).appendTo(row);
		$("<td/>").text(getPercent(yangxing,resultItems[i]['totalNumber'])).appendTo(row);
		$("<td/>").text(resultItems[i]['xibaoxueYangXing']).appendTo(row);
		$("<td/>").text(getPercent(resultItems[i]['xibaoxueYangXing'],resultItems[i]['totalNumber'])).appendTo(row);
		$("<td/>").html(getAnalyzeStaticDetails(resultItems[i]['AItemValues'])).appendTo(row);
		row.appendTo("#analyzeTable");
		if(className=='odd')
			className='even';
		else
			className='odd';
		
		toalNumberSum=toalNumberSum+resultItems[i]['totalNumber'];
		positiveNumberSum=positiveNumberSum+resultItems[i]['yinXing'];
		negativeNumberSum=negativeNumberSum+yangxing;
		negativeNumberOfCellSum=negativeNumberOfCellSum+resultItems[i]['xibaoxueYangXing'];
		
		chart_cat[i]=resultItems[i]['name'];
		chart_value_yinxing[i]=resultItems[i]['yinXing'];
		chart_value_yangxing[i]=yangxing;
		chart_value_xinbaoYangxing[i]=negativeNumberOfCellSum+resultItems[i]['xibaoxueYangXing'];
		
	}	
	var row=$("<tr/>");
	
	//appendCellToRowWithHTML("&nbsp;",row,"group_tr");
	appendCellToRow("小计",row,"group_tr");
	appendCellToRow(toalNumberSum,row,"group_tr");
	appendCellToRow(positiveNumberSum,row,"group_tr");
	appendCellToRow(getPercent(positiveNumberSum,toalNumberSum),row,"group_tr");
	
	appendCellToRow(negativeNumberSum,row,"group_tr");
	appendCellToRow(getPercent(negativeNumberSum,toalNumberSum),row,"group_tr");
	
	appendCellToRow(negativeNumberOfCellSum,row,"group_tr");
	appendCellToRow(getPercent(negativeNumberOfCellSum,toalNumberSum),row,"group_tr");
	appendCellToRow(getDetailsResultTotalNumber(),row,"group_tr");
	row.appendTo("#analyzeTable");
	/*chart_data["overall"][index]={"name":projectName,
			"totalNumber":toalNumberSum,
			"negativeNumber":negativeNumberSum,
			"positiveNumber":positiveNumberSum,
			"positiveNumberOfCell":positiveNumberOfCellSum};	*/
	loadStackedBarChart(chart_cat,chart_value_yinxing,chart_value_yangxing,chart_value_xinbaoYangxing);
}
function getAnalyzeStaticDetails(resultMap){
	if(typeof(resultMap['csqu1'])=='undefined')
		return "暂无统计数据";
	return "<table>"+
	getDetailsResult(resultMap)
	"</table>";
}

	
function getDetailsResultTotalNumber(){
	var ret='<table>';
	for(var i=0;i<fieldName.length;i++){
		ret+="<tr><td class='group_tr'>"+fieldName[i][1]+"</td><td class='group_tr'>"+fieldName[i][2]+"</td></tr>";
	}
	ret+='</table>'
	return ret;
}
function getDetailsResult(resultMap,aItemNumber){
	
	var ret='';
	for(var i=0;i<fieldName.length;i++){
		ret+="<tr><td>"+fieldName[i][1]+"</td><td>"+resultMap[fieldName[i][0]]+"</td></tr>";
		fieldName[i][2]=fieldName[i][2]+resultMap[fieldName[i][0]];
	}
	return ret;
	
}
function appendCellToRow(text,row,className){
	$("<td/>").attr("class",className).html(text).appendTo(row);
}
function appendCellToRowWithHTML(text,row,className){
	$("<td/>").attr("class",className).html(text).appendTo(row);
}
function loadChart(data,name){
	if(chart_type=="column")
	{
		loadBarChart(data,name);
	}else
	{
		loadPieChart(data,name);
	}
	
}


function repaintChart(){
	var selector=$("#selectChart");
	loadChart(chart_data[selector.val()],chart_name_data[selector.val()]);
}
var MAX_TYPE_ID=4;
function reloadChart(selector,typeId){
	if(typeId==MAX_TYPE_ID)
		return;
	if($(selector).val()==''){
		resetAllSelector(typeId);
		return;
	}
	var nextTypeId=typeId+1;
	var nextSelectorId="selector"+nextTypeId;
	$.ajax({
		   type: "GET",
		   url: API_REGION,
		   data:{"typeId":typeId,"currentId":$(selector).val()},
		   dataType:'json',
		   success: function(data){
		   		var items=data.items;
		   		$("#"+nextSelectorId).find('option').remove().end().append('<option value="">全部</option>');
		   		for(var i=0;i<items.length;i++){
		   			$("<option/>").attr("value",items[i].id).text(items[i].name).appendTo("#"+nextSelectorId);
		   		}
		   },
		   error:function(){
		   		alert("system error");
		   }
	 });
}
function resetAllSelector(typeId){
	for(var i=typeId+1;i<=MAX_TYPE_ID;i++){
		var nextSelectorId="selector"+i;
		$("#"+nextSelectorId).find('option').remove().end().append('<option value="">全部</option>');
	}
}


function loadPieChart(arrayData,chartName){
	var chart;
	var negative_total=0;
	var positive_total=0;
	for(var i=0;i<arrayData.length;i++){
		negative_total=negative_total+arrayData[i]['negativeNumber'];
		positive_total=positive_total+arrayData[i]['positiveNumber'];
	}
	var total_num=negative_total+positive_total;
	   chart = new Highcharts.Chart({
	      chart: {
	         renderTo: 'chart_container',
	         margin: [50, 200, 60, 170]
	      },
	      title: {
	         text: chartName+'：阴性/阳性占比'
	      },
	      plotArea: {
	         shadow: null,
	         borderWidth: null,
	         backgroundColor: null
	      },
	      tooltip: {
	         formatter: function() {
	            return '<b>'+ this.point.name +'</b>: '+ getPercent(this.y,total_num);
	         }
	      },
	      plotOptions: {
	         pie: {
	            allowPointSelect: true,
	            cursor: 'pointer',
	            dataLabels: {
	               enabled: true,
	               formatter: function() {
	                  if (this.y > 5) return this.point.name;
	               },
	               color: 'white',
	               style: {
	                  font: '13px Trebuchet MS, Verdana, sans-serif'
	               }
	            }
	         }
	      },
	      legend: {
	         layout: 'vertical',
	         style: {
	            left: 'auto',
	            bottom: 'auto',
	            right: '50px',
	            top: '100px'
	         }
	      },
	       series: [{
	         type: 'pie',
	         name: '统计结果',
	         data: [
	            ['阴性',negative_total],
	            ['阳性',positive_total],
	         ]
	      }]
	   });
}

function loadStackedBarChart(chart_cat,chart_value_yinxing,chart_value_yangxing,chart_value_xinbaoYangxing){
	var chart;
	$(document).ready(function() {
	   chart = new Highcharts.Chart({
	      chart: {
	         renderTo: 'chart_container',
	         defaultSeriesType: 'column'
	      },
	      title: {
	         text: '数据统计图'
	      },
	      xAxis: {
	         categories: chart_cat,
	         labels: {
	            rotation: -45,
	            align: 'right',
	            style: {
	                font: 'normal 10px Verdana, sans-serif'
	          }
         }
	         
	      },
	      yAxis: {
	         min: 0,
	         title: {
	            text: '数据统计对比图'
	         }
	      },
	      legend: {
	         backgroundColor: '#FFFFFF',
	         reversed: true,
	         style: {
	            left: 'auto',
	            bottom: 'auto',
	            right: '50px',
	            top: '100px'
	         }
	      },
	      tooltip: {
	         formatter: function() {
	            return ''+
	                this.series.name +': '+ this.y +'';
	         }
	      },
	      plotOptions: {
	         series: {
	            stacking: 'normal',
	            dataLabels: {
            		enabled: false,
		            rotation: -90,
		            color: '#FFFFFF',
		            align: 'right',
		            x: -3,
		            y: 10,
		            formatter: function() {
		               return this.y;
		            },
		            style: {
		               font: 'normal 13px Verdana, sans-serif'
		            }
         		}  
	         }
	      },
	           series: [{
	         name: '阴性标本例数',
	         data: chart_value_yinxing
	      }, {
	         name: '阳性标本例数',
	         data: chart_value_yangxing
	      }, {
	         name: '细胞学阳性标本例数',
	         data: chart_value_xinbaoYangxing
	      }]
	   });
	   
	   
	});
	

}

function loadBarChart(arrayData,chartName){
	var chart;
	var categoriesArray=new Array(arrayData.length);
	var totalDataArray=new Array(arrayData.length);
	var negativeDataArray=new Array(arrayData.length);
	var positiveDataArray=new Array(arrayData.length);
	var positiveNumberOfCellDataArray=new Array(arrayData.length);
	for(var i=0;i<arrayData.length;i++){
		categoriesArray[i]=arrayData[i]['name'];
		totalDataArray[i]=arrayData[i]['totalNumber'];
		negativeDataArray[i]=arrayData[i]['negativeNumber'];
		positiveDataArray[i]=arrayData[i]['positiveNumber'];
		positiveNumberOfCellDataArray[i]=arrayData[i]['positiveNumberOfCell'];
	}
	chart = new Highcharts.Chart({
	      chart: {
	         renderTo: 'chart_container',
	         defaultSeriesType: 'column'
	      },
	      title: {
	         text: chartName
	      },
	      subtitle: {
	         text: 'Source: 医疗信息管理系统'
	      },
	      xAxis: {
	         categories: categoriesArray
	      },
	      yAxis: {
	         min: 0,
	         title: {
	            text: '标本数'
	         }
	      },
	      legend: {
	         layout: 'vertical',
	         backgroundColor: '#FFFFFF',
	         align: 'left',
	         verticalAlign: 'top',
	         x: 100,
	         y: 70
	      },
	      tooltip: {
	         formatter: function() {
	            return ''+
	               this.x +': '+this.y+'例' ;
	         }
	      },
	      plotOptions: {
	         column: {
	            pointPadding: 0.2,
	            borderWidth: 0
	         }
	      },
	           series: [{
	         name: '标本总数',
	         data: totalDataArray
	   
	      }, {
	         name: '阴性标本数',
	         data: negativeDataArray
	   
	      }, {
	         name: '阳性标本数',
	         data: positiveDataArray
	   
	      }, {
	         name: '细胞学阳性例数',
	         data: positiveNumberOfCellDataArray
	   
	      }]
	   });

}

